import { defineStore } from 'pinia'
import { constantRoutes } from '@/router'
import { getRoutes } from '@/api/menu'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    addRoutes: []
  }),

  actions: {
    // 生成路由
    async generateRoutes(roles) {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = await this.getAsyncRoutes()
      } else {
        accessedRoutes = await this.filterAsyncRoutes(await this.getAsyncRoutes(), roles)
      }
      this.addRoutes = accessedRoutes
      this.routes = constantRoutes.concat(accessedRoutes)
      return accessedRoutes
    },

    // 获取异步路由
    async getAsyncRoutes() {
      const { data } = await getRoutes()
      return data
    },

    // 过滤异步路由
    filterAsyncRoutes(routes, roles) {
      const res = []
      routes.forEach(route => {
        const tmp = { ...route }
        if (this.hasPermission(roles, tmp)) {
          if (tmp.children) {
            tmp.children = this.filterAsyncRoutes(tmp.children, roles)
          }
          res.push(tmp)
        }
      })
      return res
    },

    // 检查权限
    hasPermission(roles, route) {
      if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
      } else {
        return true
      }
    }
  }
})
